package com.itobase.statusDetect.Service.impl;

import com.itobase.statusDetect.Model.Camera;
import com.itobase.statusDetect.Model.Classroom;
import com.itobase.statusDetect.Model.Time;
import com.itobase.statusDetect.Repository.CameraRepository;
import com.itobase.statusDetect.Service.CameraService;
import com.itobase.statusDetect.Util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.InvalidParameterException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author htyu
 * @date 2019/2/24
 */
@Service
public class CameraServiceImpl implements CameraService {

    @Autowired
    CameraRepository cameraRepository;

    @Override
    public Camera create(Camera camera){
        checkExist(camera.getName());
        return cameraRepository.save(camera);
    }

    @Override
    public Camera detial(String id) {
        return cameraRepository.findById(id).get();
    }

    @Override
    public Camera updateCamera(Camera camera) {
        String name = camera.getName();
        checkExist(name);
        Camera camera_new = cameraRepository.findByName(name);
        camera_new.setStatus(camera.getStatus());
        camera_new.setAccount(camera.getAccount());
        camera_new.setName(camera.getName());
        camera_new.setPassword(camera.getPassword());
        camera_new.setSerialNumber(camera.getSerialNumber());
        return cameraRepository.save(camera_new);
    }


    @Override
    public List<Camera> getList(String keyword) {
        List<Camera> list = cameraRepository.findAll();
        List<Camera> result;
        if(StringUtils.isNotEmpty(keyword)){
            result = list.stream().filter(camera ->
                            camera.getName().contains(keyword)||
                            camera.getSerialNumber().toLowerCase().contains(keyword.toLowerCase())||
                            camera.getStatus().contains(keyword)||
                            camera.getAccount().toLowerCase().contains(keyword.toLowerCase())||
                            camera.getPassword().toLowerCase().contains(keyword.toLowerCase()))
                    .collect(Collectors.toList());
        }else{
            result = list;
        }
        return result;
    }

    private void checkExist(String name) {
        Camera camera = cameraRepository.findByName(name);
        if (camera!=null)
            throw new InvalidParameterException("球机名重复,请勿重复添加");
    }
}
